/*_____________________________________________________________________________

                               fun_dna_manipulation.sql

  These are python functions to reverse and/or complement DNA sequences
  NB: 'U' is converted to 'A'. 'A' complement is 'T', not 'U'
  NB: Characters other than ACGTU are not converted.
______________________________________________________________________________*/

-- CREATE LANGUAGE "plpythonu";

------------[ This is a general pourpose function to reverse strings ]---------

CREATE OR REPLACE FUNCTION "reverse_string"(x text)
  RETURNS text
AS $$

rx= x[::-1]
return rx

$$ LANGUAGE plpythonu;

-------------------[ DNA complement of a RNA or DNA sequence]------------------

CREATE OR REPLACE FUNCTION "dna_comp"(x text)
  RETURNS text
AS $$

xv= list(x)

complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'U':'A'}

cx=[]
for base in xv:
    if base in complement:
        cx.append(complement[base])
    else:
        cx.append(base)  ## Bases other than ACGT are not converted to anything

cx= ''.join(cx)

return cx

$$ LANGUAGE plpythonu;

------------[ DNA reverse complement of a RNA or DNA sequence ]----------------

CREATE OR REPLACE FUNCTION "dna_revcomp"(x text)
  RETURNS text
AS $$

rx= x[::-1] ## reverse
rx= list(rx)

complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'U':'A'}

rcx=[]
for base in rx:
    if base in complement:
        rcx.append(complement[base])
    else:
        rcx.append(base)  ## Bases other than ACGT are not converted to anything

rcx= ''.join(rcx)

return rcx

$$ LANGUAGE plpythonu;